#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include<QWidget>
#include<QVBoxLayout>
#include<QLabel>
#include<QDialog>
#include<QDesktopServices>
#include <QFileDialog>
#include <QDir>
#include <QDebug>
#include<QStringList>
#include<QTextEdit>
#include<QInputDialog>
#include <QMenu>
#include <QAction>
#include<QMap>
#include<QMessageBox>
#include <QFileInfo>
#include<QVBoxLayout>
#include<QCheckBox>
QMap<QString,QString> filePathAndNameMap;
QMap<QString,QString> filePathAndNameMapNote;
QMap<QString,QString> filePathAndNameMapCode;
QMap<QString,QString> filePathAndNameMapTypora;
QMap<QString,QStringList> CourseMap;
QString inputDiglogstyleSheet = R"(
    QLabel {
        color: black;
    font-weight: bold;
    }
    QLineEdit {
        background-color: #424242;
        color: white;
        selection-background-color: #64b5f6;
        border: 1px solid #64b5f6;
        border-radius: 3px;
        padding: 0 8px;    font-weight: bold;
    }
    QPushButton {
        background-color: #64b5f6;
        color: #ffffff;
        border: none;
        border-radius: 3px;
        padding: 5px 16px;
    }
    QPushButton:hover {
        background-color: #82c7ff;
    }
    QPushButton:pressed {
        background-color: #4e92cc;
    }
)";
QString pathQtVideo="D:/Qt Video";
QString pathCplusplusVideo="D:/C++录播";
QString pathCVideo="D:/c语言录播";

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    ,settings("LearningSerach","FileInfo")
    ,welcomesettings("LearningSerachWelcomeinfo","info")
{
    setWindowIcon(QIcon("taskicon.ico"));
    loadSettings();
    ui->setupUi(this);
    welcomesettingsinit();
    // 创建一个 QLabel 作为占位文本
    QLabel *placeholderLabel = new QLabel("这里还没有内容，请添加一些项目。", this);

    // 使用 QVBoxLayout 将 QListWidget 和 QLabel 叠加在一起
    QVBoxLayout *overlayLayout = new QVBoxLayout(ui->listWidget);
    overlayLayout->addWidget(placeholderLabel, 0, Qt::AlignCenter);

    // 设置 QLabel 的样式
    placeholderLabel->setStyleSheet("color: #888; font-style: italic;");

    // 根据 QListWidget 中的项目数量更新 QLabel 的可见性
    auto updatePlaceholderVisibility = [this, placeholderLabel]() {
        placeholderLabel->setVisible(ui->listWidget->count() == 0);
    };

    // 当 QListWidget 中的项目数量发生变化时，更新 QLabel 的可见性
    connect(ui->listWidget->model(), &QAbstractItemModel::rowsInserted, updatePlaceholderVisibility);
    connect(ui->listWidget->model(), &QAbstractItemModel::rowsRemoved, updatePlaceholderVisibility);

    // 初始化 QLabel 的可见性
    updatePlaceholderVisibility();
    QStringList courseList = CourseMap.value("CourseTitle");
    for(QStringList::Iterator it=courseList.begin();it!=courseList.end();it++)
    {
        ui->comboBox->addItem(*it);
    }
    ui->listWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    //connect(ui->listWidget, &QListWidget::customContextMenuRequested,
    //        this, &MainWindow::on_listWidget_customContextMenuRequested);


    this->setWindowIcon(QIcon("://Resoures/taskicon.png"));
    this->setStyleSheet(R"(

        QMenu {
            background-color: #1e3b5a;
            border: 1px solid #4a8bbd;
        }
        QMenu::item {
            color: #ffffff;
            padding: 5px 30px 5px 30px;
        }
        QMenu::item:selected {
            background-color: #4a8bbd;
        }
        QScrollBar:vertical {
            background: #1e3b5a;
            width: 15px;
            margin: -30px 0 -30px 0;
            border: 1px solid #4a8bbd;
        }

        QScrollBar::handle:vertical {
            background: #4a8bbd;
            min-height: 20px;
            border-radius: 7px;
        }

        QScrollBar::add-line:vertical {
            background: none;
            height: 15px;
            subcontrol-position: bottom;
            subcontrol-origin: margin;
        }

        QScrollBar::sub-line:vertical {
            background: none;
            height: 15px;
            subcontrol-position: top;
            subcontrol-origin: margin;
        }

        QScrollBar:horizontal {
            background: #1e3b5a;
            height: 15px;
            margin: 0 15px 0 15px;
            border: 1px solid #4a8bbd;
        }

        QScrollBar::handle:horizontal {
            background: #4a8bbd;
            min-width: 20px;
            border-radius: 7px;
        }

        QScrollBar::add-line:horizontal {
            background: none;
            width: 15px;
            subcontrol-position: right;
            subcontrol-origin: margin;
        }

        QScrollBar::sub-line:horizontal {
            background: none;
            width: 15px;
            subcontrol-position: left;
            subcontrol-origin: margin;
        }

QComboBox {
    border: 1px solid #2980b9;
    border-radius: 3px;
    padding: 1px 18px 1px 3px;
    min-width: 6em;
    color: #2c3e50;
    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ecf0f1, stop: 1 #bdc3c7);
    font-size: 15px;
    font-weight: bold;
}

QComboBox::drop-down {
    subcontrol-origin: padding;
    subcontrol-position: top right;
    width: 15px;
    border-left-width: 1px;
    border-left-color: #2980b9;
    border-left-style: solid;
    border-top-right-radius: 3px;
    border-bottom-right-radius: 3px;
}

QComboBox::down-arrow {
    image: url(:/Resoures/droparrow.png);
    width: 20px;
    height: 20px;
}

QComboBox::down-arrow:on {
    top: 1px;
}

QComboBox:hover {
    border: 1px solid #3cb0fd;
}

QComboBox::drop-down:hover {
    border-left-color: #3cb0fd;
}

QComboBox:on {
    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #bdc3c7, stop: 1 #95a5a6);
}

/* QListWidget */
QListWidget {
    background-color: #ecf0f1;
    color: #34495e;
    border: 1px solid #3498db;
    border-radius: 4px;
    font-size: 17px;
    font-weight: bold;
}

QListWidget::item:hover {
    background-color: #bdc3c7;
    color: #34495e;
}

QListWidget::item:selected {
    background-color: #3498db;
    color: white;
}

QListWidget::item:selected:!active {
    background-color: #95a5a6;
    color: white;
}

/* QMainWindow */
QMainWindow {
    background-color: #e0e6f0;
    border: 1px solid #3498db;
    border-radius: 4px;
}
)");
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::saveVideoDirectories(const QStringList &directories)
{
    QJsonArray jsonArray;
    for (const QString &dir : directories) {
        jsonArray.append(dir);
    }

    QJsonObject jsonObject;
    jsonObject["directories"] = jsonArray;

    QJsonDocument jsonDoc(jsonObject);
    QFile file("video_directories.json");
    if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        file.write(jsonDoc.toJson());
        file.close();
    }
}

QStringList MainWindow::loadVideoDirectories()
{
    QStringList directories;

    QFile file("video_directories.json");
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QByteArray jsonData = file.readAll();
        file.close();

        QJsonDocument jsonDoc(QJsonDocument::fromJson(jsonData));
        QJsonObject jsonObject = jsonDoc.object();
        QJsonArray jsonArray = jsonObject["directories"].toArray();

        for (const QJsonValue &value : jsonArray) {
            directories.append(value.toString());
        }
    }

    return directories;
}

void MainWindow::saveSettings(const QMap<QString, QString> &fileMap)
{
    /*VideoMap"
NoteMap",
CodeoMap"
TyporaMap*/
    if (fileMap.contains("VideoMap")) {
        settings.beginGroup("FileMap");
    } else if (fileMap.contains("NoteMap")) {
        settings.beginGroup("FileNoteMap");
    } else if (fileMap.contains("CodeoMap")) {
        settings.beginGroup("FileCodeMap");
    } else if (fileMap.contains("TyporaMap")) {
        settings.beginGroup("FileTyporaMap");
    } else if(fileMap.contains("CourseTitle")){
        settings.beginGroup("Course");
    }else{
        return;
    }

    settings.remove("");
    for (auto key : fileMap.keys()) {
            settings.setValue(key, fileMap.value(key));
    }
    settings.endGroup();

}

void MainWindow::saveCourseSettings(const QMap<QString, QStringList> &fileMap)
{
    settings.beginGroup("Course");
    for (auto key : fileMap.keys()) {
        if(key=="CourseTitle")
        {
            QStringList CourseTitlestr=fileMap.value("CourseTitle");
            settings.setValue("CourseTitle",CourseTitlestr);
        }
        else
        {
            QStringList CourseTitlestr=fileMap.value("CourseTitle");
            for(auto Specifytasktitle:CourseTitlestr)
            {
                settings.setValue(Specifytasktitle,fileMap.value(Specifytasktitle));
            }
        }
    }

}

void MainWindow::loadSettings()
{
    /*VideoMap"
NoteMap",
CodeoMap"
TyporaMap*/
    settings.beginGroup("FileMap");
    QStringList keys1=settings.childKeys();
    for(auto key:keys1)
    {
        filePathAndNameMap.insert(key,settings.value(key).toString());
    }
    settings.endGroup();
    settings.beginGroup("FileNoteMap");
    QStringList keys2=settings.childKeys();
    for(auto key:keys2)
    {
        filePathAndNameMapNote.insert(key,settings.value(key).toString());
    }
    settings.endGroup();
    settings.beginGroup("FileCodeMap");
    QStringList keys3=settings.childKeys();
    for(auto key:keys3)
    {
        filePathAndNameMapCode.insert(key,settings.value(key).toString());
    }
    settings.endGroup();
    settings.beginGroup("FileTyporaMap");
    QStringList keys4=settings.childKeys();
    for(auto key:keys4)
    {
        filePathAndNameMapTypora.insert(key,settings.value(key).toString());
    }
    settings.endGroup();
    settings.beginGroup("Course");
    QStringList keys5=settings.childKeys();
    for(auto key:keys5)
    {
        if(key=="CourseTitle")
        {
            CourseMap.insert("CourseTitle",settings.value(key).toStringList());
            //CourseMap.insert("CourseTitle",settings.value(key).toString());
            //CourseMap.insert(settings.value(key).toString()
            //                 ,settings.value(settings.value(key).toString()).toString());
        }
        else
        {
            CourseMap.insert(key,settings.value(key).toStringList());
        }
    }
    settings.endGroup();
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    QMessageBox msgBox;

    msgBox.setStyleSheet("QMessageBox {     background-color: #e0e6f0; }"
                         "QPushButton { background-color: #303f9f; border: none; color: white; min-width: 80px; min-height: 30px; }"
                         "QPushButton:hover { background-color: #5c6bc0; }"
                         "QLabel { color: black; }");
    msgBox.setWindowIcon(QIcon("://Resoures/taskicon.png"));
    msgBox.setIcon(QMessageBox::Question);
    msgBox.setWindowTitle("退出确认");
    msgBox.setText("确定要退出程序吗？");
    QPushButton *yesButton = msgBox.addButton(tr("是"), QMessageBox::YesRole);
    msgBox.addButton(tr("否"), QMessageBox::NoRole);

    msgBox.exec();

    if (msgBox.clickedButton() == yesButton) {
        filePathAndNameMap.insert("VideoMap","Vm");
        filePathAndNameMapNote.insert("NoteMap","Nm");
        filePathAndNameMapCode.insert("CodeoMap","Cm");
        filePathAndNameMapTypora.insert("TyporaMap","Tm");
        saveSettings(filePathAndNameMap);
        saveSettings(filePathAndNameMapCode);
        saveSettings(filePathAndNameMapTypora);
        saveSettings(filePathAndNameMapNote);
        saveCourseSettings(CourseMap);
        event->accept();
    } else {
        event->ignore();
    }
}

void MainWindow::welcomesettingsinit()
{
    bool showWelcomeMessage = settings.value("ShowWelcomeMessage", true).toBool();
    QString messageBoxStyle = R"(
    QMessageBox {
        background-color: #3498db;
        color: white;
        font-size: 14px;
        font-weight: bold;
        border-radius: 8px;
    }
    QLabel {
        color: white;
    }
    QPushButton {
        background-color: #3498db;
        color: white;
        border: 2px solid #2980b9;
        border-radius: 4px;
        padding: 5px;
        font-size: 14px;
        font-weight: bold;
        text-align: center;
        outline: none;
    }
    QPushButton:hover {
        background-color: #3cb0fd;
        border: 2px solid #2a8fd4;
    }
    QPushButton:pressed {
        background-color: #2980b9;
        border: 2px solid #216f9c;
    }
    QPushButton:disabled {
        background-color: #3498db;
        color: #c0c0c0;
        border: 2px solid #2980b9;
    }
    )";

    QString checkBoxStyle = R"(
    QCheckBox {
        spacing: 5px;
        color: white;
    }
    QCheckBox::indicator {
        width: 13px;
        height: 13px;
        border: 2px solid white;
        border-radius: 2px;

    }
    QCheckBox::indicator:checked {
            image: url(:/Resoures/1.png);
        border: 2px solid white;
    }
    )";
    if (showWelcomeMessage) {
        QMessageBox welcomeMessage(this);
        welcomeMessage.setWindowTitle("欢迎使用编程宝典");
        welcomeMessage.setText("轻松管理编程学习资源，让编程之路更加高效！欢迎来体验我们的全新App —— 『课题查看器』！🚀\n\n"
                                "📚 个性化课程分类，涵盖各种编程课题：C语言程序设计、数据结构、算法分析等，一目了然！\n"
                                "💡 高效整理课题知识点，指针操作、函数封装、类继承等，尽在掌握！\n\n"
                                "🌟 用户为中心，自由添加、删除课题和知识点，让学习体验更贴心！\n\n"
                                "🔖 『编程宝典』助你整合手头学习资源：\n"
                                "🔸 自主添加源码示例，轻松管理实用编程案例，助力技能提升！\n"
                                "🔸 整理笔记心得，学习感悟一键记录，随时查阅，告别遗忘！\n"
                                "🔸 汇集教学视频，专业导师线上授课，一手掌握，理解编程概念！\n\n"
                                "🌱 不论你是编程新手还是资深开发者，『编程宝典』都是你的学习管理利器！加入我们，开启编程之旅，实现学习资源的高效管理吧！反馈渠道：292370306@qq.com");
        QCheckBox dontShowAgain("下次不再提醒");
        dontShowAgain.blockSignals(true);
        welcomeMessage.setCheckBox(&dontShowAgain);
        welcomeMessage.setStyleSheet(messageBoxStyle);
        welcomeMessage.setWindowIcon(QIcon(":/Resoures/taskicon.png"));
        dontShowAgain.setStyleSheet(checkBoxStyle);
        welcomeMessage.exec();

        // Save the user's choice
        settings.setValue("ShowWelcomeMessage", !dontShowAgain.isChecked());
    }
}


void MainWindow::on_comboBox_currentIndexChanged(int index)
{
    ui->listWidget->clear();
    QStringList courseStringlist = CourseMap.value("CourseTitle");
    for(auto taskName:courseStringlist)
    {
        if(ui->comboBox->itemText(index)==taskName)
        {
            QStringList SpeciflyCourse=CourseMap.value(taskName);
            for(QStringList::Iterator it=SpeciflyCourse.begin();it!=SpeciflyCourse.end();it++)
            {
                ui->listWidget->addItem(*it);
            }
        }
    }
}

void MainWindow::on_actionAdd_New_Task_triggered()
{
    QString dir = QFileDialog::getExistingDirectory(this, "选择视频目录");
    if (!dir.isEmpty()) {
        QStringList directories = loadVideoDirectories();
        directories.append(dir);
        saveVideoDirectories(directories);
    }
}


void MainWindow::on_listWidget_itemDoubleClicked(QListWidgetItem *item)
{
    widget=new QDialog;
    widget->setStyleSheet(R"(
    QPushButton {
        background-color: #3498db;
        color: white;
        border: 2px solid #2980b9;
        border-radius: 4px;
        padding: 5px;
        font-size: 14px;
        font-weight: bold;
        text-align: center;
        outline: none;
    }
    QPushButton:hover {
        background-color: #3cb0fd;
        border: 2px solid #2a8fd4;
    }
    QPushButton:pressed {
        background-color: #2980b9;
        border: 2px solid #216f9c;
    }
    QPushButton:disabled {
        background-color: #3498db;
        color: #c0c0c0;
        border: 2px solid #2980b9;
    }
QLabel {
    color: #2c3e50;
    font-size: 14px;
    font-weight: bold;
    border: 1px solid #bdc3c7;
    border-radius: 4px;
    padding: 5px;
    background-color: #ecf0f1;
    text-align: center;
}
)");
    widget->setAttribute(Qt::WA_DeleteOnClose);
    widget->setWindowFlags(Qt::FramelessWindowHint);
    QPushButton* codefileopen=new QPushButton("打开源码");
    QPushButton* notefileopen=new QPushButton("打开笔记");
    QPushButton* typorafileopen=new QPushButton("打开typora文档");
    QPushButton* videofileopen=new QPushButton("打开教学视频");
    closebtn=new QPushButton("取消选择");
    auto vlayout=new QVBoxLayout;
    vlayout->setDirection(QVBoxLayout::TopToBottom);
    vlayout->addWidget(new QLabel("请选择打开方式:"));
    vlayout->addWidget(codefileopen);
    vlayout->addWidget(notefileopen);
    vlayout->addWidget(typorafileopen);
    vlayout->addWidget(videofileopen);
    vlayout->addWidget(closebtn);
    widget->setLayout(vlayout);
    connect(closebtn,&QPushButton::clicked,widget,[=]()
    {
        widget->close();
    });
    connect(codefileopen,&QPushButton::clicked,widget,[=]()
    {
        QString currentDirPath = filePathAndNameMapCode.value(item->text()); // 假设这是从item获取的目录路径
        // 使用QFileInfo获取上级目录的路径
        if(!currentDirPath.isEmpty())
        {
            QFileInfo fileInfo(currentDirPath);
            QString parentDirPath = fileInfo.dir().absolutePath();
            QDesktopServices::openUrl(QUrl::fromLocalFile(parentDirPath));
        }
        else
        {
            QMessageBox::information(this,"提示","您没有为此课程添加源码");
        }
    });
    connect(notefileopen,&QPushButton::clicked,widget,[=]()
    {
        QString currentDirPath = filePathAndNameMapNote.value(item->text()); // 假设这是从item获取的目录路径
        // 使用QFileInfo获取上级目录的路径
        if(!currentDirPath.isEmpty())
        {
            QFileInfo fileInfo(currentDirPath);
            QString parentDirPath = fileInfo.dir().absolutePath();
            QDesktopServices::openUrl(QUrl::fromLocalFile(parentDirPath));
        }
        else
        {
            QMessageBox::information(this,"提示","您没有为此课程添加笔记");
        }
    });
    connect(typorafileopen,&QPushButton::clicked,widget,[=]()
    {
        QString currentDirPath = filePathAndNameMapTypora.value(item->text()); // 假设这是从item获取的目录路径
        // 使用QFileInfo获取上级目录的路径
        if(!currentDirPath.isEmpty())
        {
            QFileInfo fileInfo(currentDirPath);
            QString parentDirPath = fileInfo.dir().absolutePath();
            QDesktopServices::openUrl(QUrl::fromLocalFile(parentDirPath));
        }
        else
        {
            QMessageBox::information(this,"提示","您没有为此课程添加Typroa文档");
        }
    });
    connect(videofileopen,&QPushButton::clicked,widget,[=]()
    {
        QString currentDirPath = filePathAndNameMap.value(item->text()); // 假设这是从item获取的目录路径
        // 使用QFileInfo获取上级目录的路径
        if(!currentDirPath.isEmpty())
        {
            QFileInfo fileInfo(currentDirPath);
            QString parentDirPath = fileInfo.dir().absolutePath();
            QDesktopServices::openUrl(QUrl::fromLocalFile(parentDirPath));
        }
        else
        {
            QMessageBox::information(this,"提示","您没有为此课程添加教学视频");
        }
    });
    widget->setModal(true);
    widget->show();
}


void MainWindow::on_pushButton_clicked()
{
    QString newtask;


    QInputDialog inputDialog(this);
    inputDialog.setModal(true);
    inputDialog.setStyleSheet(inputDiglogstyleSheet);
    inputDialog.setWindowTitle(tr("创建新课题"));
    inputDialog.setLabelText(tr("请输入新课题名称:"));
    inputDialog.setTextValue("");
    inputDialog.setTextEchoMode(QLineEdit::Normal);

    if (inputDialog.exec() == QDialog::Accepted) {
        QString text = inputDialog.textValue();
        if (!text.isEmpty()) {
            // 用户输入了内容并按下了回车
            qInfo() << "User input:" << text;
            // 在此处处理用户输入的内容
            newtask=text;
        }
    }
    if(!newtask.isEmpty())
    {
        ui->comboBox->addItem(newtask);
        QStringList CourseTitles=CourseMap.value("CourseTitle");
        CourseTitles.append(newtask);
        CourseMap.insert("CourseTitle",CourseTitles);
    }
}


void MainWindow::on_listWidget_customContextMenuRequested(const QPoint &pos)
{
    QMenu menu(this);

        QAction *addAction = new QAction(tr("添加新课程"), this);
        QAction *addActioncode = new QAction(tr("为课程添加源码示例目录"), this);
        QAction *addActionnote = new QAction(tr("为课程添加笔记目录"), this);
        QAction *addActiontypora = new QAction(tr("为课程添加typora文档目录"), this);
        QAction *addActionvideo = new QAction(tr("为课程添加教学视频目录"), this);
        QAction *deleteAction = new QAction(tr("删除选中课程"), this);

        // 添加菜单项
        if (ui->listWidget->itemAt(pos)) {
            menu.addAction(addActioncode);
            menu.addAction(addActionnote);
            menu.addAction(addActiontypora);
            menu.addAction(addActionvideo);
            menu.addAction(deleteAction);
        }
        menu.addSeparator();
        menu.addAction(addAction);
        // 连接信号和槽
        connect(addAction, &QAction::triggered, [this]() {
            bool hasItems = ui->comboBox->count() > 0;
            if(!hasItems)
            {
                QMessageBox::information(this,"提示","您还没有添加课题，求点击右上角加号添加课题后再添加课程");
            }
            else
            {
                QInputDialog inputDialog;
                inputDialog.setModal(true);
                //inputDialog.setWindowFlags(Qt::FramelessWindowHint);
                inputDialog.setStyleSheet(inputDiglogstyleSheet);
                inputDialog.setWindowTitle("添加新课程");
                inputDialog.setLabelText(tr("请输入新课程名称:"));
                inputDialog.setTextValue("");
                inputDialog.setTextEchoMode(QLineEdit::Normal);
                inputDialog.show();
                QString text;
                if (inputDialog.exec() == QDialog::Accepted) {
                    text = inputDialog.textValue();
                    if (!text.isEmpty()) {
                        // 用户输入了内容并按下了回车
                        qInfo() << "User input:" << text;
                        // 在此处处理用户输入的内容
                    }
                }
                if (!text.isEmpty()) {
                    ui->listWidget->addItem(text);
                    QStringList CourseTitles=CourseMap.value(ui->comboBox->currentText());
                    CourseTitles.append(text);
                    CourseMap.insert(ui->comboBox->currentText(),CourseTitles);
                }
            }
        });

        connect(deleteAction, &QAction::triggered, [this, pos]() {
            QStringList CourseTitles=CourseMap.value(ui->comboBox->currentText());
            CourseTitles.removeAll(ui->listWidget->itemAt(pos)->text());
            CourseMap.insert(ui->comboBox->currentText(),CourseTitles);
            delete ui->listWidget->itemAt(pos);

        });
        connect(addActioncode, &QAction::triggered, [this, pos]() {
            QDir videodirectory=QFileDialog::getExistingDirectory(this,"选择源码目录",QDir::homePath());
            QStringList filenames=videodirectory.entryList(QDir::Files | QDir::NoDotAndDotDot|QDir::Dirs);
            QStringList filespath;
            for(auto filename:filenames)
            {
                filespath.append(videodirectory.absoluteFilePath(filename));
            }
            QListWidgetItem* item=ui->listWidget->itemAt(pos);
            if (!item) {
                return;
            }
            for(auto filepath:filespath)
            {
                filePathAndNameMapCode.insert(item->text(),filepath);
            }
        });
        connect(addActiontypora, &QAction::triggered, [this, pos]() {
            QDir videodirectory=QFileDialog::getExistingDirectory(this,"选择Typora目录",QDir::homePath());
            QStringList filenames=videodirectory.entryList(QDir::Files | QDir::NoDotAndDotDot|QDir::Dirs);
            QStringList filespath;
            for(auto filename:filenames)
            {
                filespath.append(videodirectory.absoluteFilePath(filename));
            }
            QListWidgetItem* item=ui->listWidget->itemAt(pos);
            if (!item) {
                return;
            }
            for(auto filepath:filespath)
            {
                filePathAndNameMapTypora.insert(item->text(),filepath);
            }
        });
        connect(addActionvideo, &QAction::triggered, [this, pos]() {
               QDir videodirectory=QFileDialog::getExistingDirectory(this,"选择视频目录",QDir::homePath());
               QStringList filenames=videodirectory.entryList(QDir::Files | QDir::NoDotAndDotDot|QDir::Dirs);
               QStringList filespath;
               for(auto filename:filenames)
               {
                   filespath.append(videodirectory.absoluteFilePath(filename));
               }
               QListWidgetItem* item=ui->listWidget->itemAt(pos);
               if (!item) {
                   return;
               }
               for(auto filepath:filespath)
               {
                   filePathAndNameMap.insert(item->text(),filepath);
               }
        });
        connect(addActionnote, &QAction::triggered, [this, pos]() {
            QDir videodirectory=QFileDialog::getExistingDirectory(this,"选择笔记目录",QDir::homePath());
            QStringList filenames=videodirectory.entryList(QDir::Files | QDir::NoDotAndDotDot|QDir::Dirs);
            QStringList filespath;
            for(auto filename:filenames)
            {
                filespath.append(videodirectory.absoluteFilePath(filename));
            }
            QListWidgetItem* item=ui->listWidget->itemAt(pos);
            if (!item) {
                return;
            }
            for(auto filepath:filespath)
            {
                filePathAndNameMapNote.insert(item->text(),filepath);
            }
        });
        // 显示菜单
        menu.exec(ui->listWidget->mapToGlobal(pos));

}


void MainWindow::on_pushButton_2_clicked()
{

    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "删除确认", "您确定要删除当前课题吗?",
                                  QMessageBox::Yes | QMessageBox::No);
    if (reply == QMessageBox::Yes) {
        if(!ui->comboBox->count()>0)
        {
            QMessageBox::information(this,"提示","您没有添加任何课题");
        }
        int currentIndex = ui->comboBox->currentIndex();
        if (currentIndex != -1) {
            QStringList CourseTitles=CourseMap.value("CourseTitle");
            QString currentText = ui->comboBox->currentText();
            QMutableStringListIterator it(CourseTitles);
            while (it.hasNext()) {
                if (it.next() == currentText) {
                    it.remove();
                }
            }
            ui->comboBox->removeItem(currentIndex);
            CourseMap.insert("CourseTitle",CourseTitles);
        }
        ui->listWidget->clear();
    }

    int currentIndex = ui->comboBox->currentIndex();
    // 如果仍然有条目存在，则将当前索引设置为下一个条目，或者如果已经到达末尾，则设置为上一个条目
    if (ui->comboBox->count() > 0) {
        if (currentIndex < ui->comboBox->count()) {
            ui->comboBox->setCurrentIndex(currentIndex);
        } else {
            ui->comboBox->setCurrentIndex(currentIndex - 1);
        }

        QString currentCourse = ui->comboBox->currentText();
        QStringList specificCourse = CourseMap.value(currentCourse);
        for (const QString& listItem : specificCourse) {
            ui->listWidget->addItem(listItem);
        }
    }
}

